package com.shishi.fast.common.util;

import com.shishi.fast.common.exception.ApiException;
import com.shishi.fast.common.vo.ResultCode;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.DigestUtils;

import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @项目名称：dbscale
 * @类描述：
 * @类创建人：lhf
 * @类创建时间：2020/12/13
 */
public class CommonUtils {

    private static Random random = new Random();

    /**
     * 描述：获取 0~(num-1) 之间的int随机数
     */
    public static int getRandom(int num) {
        if (num < 0) {
            return 0;
        }
        return random.nextInt(num);
    }

    /**
     * 描述：生成4位数短信验证码
     */
    public static String getSmsCode() {
        return String.format("%04d", random.nextInt(10000));
    }

    /**
     * 验证手机号格式
     */
    public static void validatorPhone(String phone) throws ApiException {
        String regex = "^((13[0-9])|(14[5,7,9])|(15([0-3]|[5-9]))|(166)|(17[0,1,3,5,6,7,8])|(18[0-9])|(19[8|9]))\\d{8}$";
        if (StringUtils.isBlank(phone)) {
            throw new ApiException(ResultCode.VALIDATE_FAILED, "手机号不能为空");
        } else {
            Pattern p = Pattern.compile(regex);
            Matcher m = p.matcher(phone);
            boolean isMatch = m.matches();
            if (!isMatch) {
                throw new ApiException(ResultCode.VALIDATE_FAILED, "请填入正确的手机号");
            }
        }
    }

    /**
     * 对字符串进行MD5加密
     */
    public static String md5(String value) {
        String md5Password = DigestUtils.md5DigestAsHex(value.getBytes());
        return md5Password;
    }

    /**
     * 获取指定位数随机数字
     */
    public static String getRandomNumber(Integer num) {
        String base = "0123456789";
        Random random = new Random();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < num; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }

    /**
     * 获取指定位数随机字符串
     */
    public static String getRandomString(Integer num) {
        String base = "abcdefghijklmnopqrstuvwxyz0123456789";
        Random random = new Random();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < num; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }
}
